const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
const morgan = require('morgan');
const dotenv = require('dotenv');
const connectDB = require('./config/db');
const { notFound, errorHandler } = require('./middleware/error');
const userRoutes = require('./routes/userRoutes');
const healthRoutes = require('./routes/healthRoutes');
const testRoutes = require('./routes/testRoutes');
const reminderRoutes = require('./routes/reminderRoutes');
const dietRoutes = require('./routes/dietRoutes');
const exerciseRoutes = require('./routes/exerciseRoutes');
const deviceRoutes = require('./routes/deviceRoutes');
const healthKnowledgeRoutes = require('./routes/healthKnowledgeRoutes');
const foodRoutes = require('./routes/foodRoutes');
const { initializeCommonFoods } = require('./controllers/foodController');
const { initializeRecipes } = require('./controllers/recipeController');
const { initializeHealthKnowledge } = require('./utils/healthKnowledgeSeed');

// 加载环境变量
dotenv.config();

// 连接数据库
connectDB();

// 初始化食物数据库（仅首次启动时添加初始数据）
initializeCommonFoods().catch(console.error);

// 初始化食谱数据库（仅首次启动时添加初始数据）
initializeRecipes().catch(console.error);

// 初始化健康知识库（仅首次启动时添加初始数据）
initializeHealthKnowledge().catch(console.error);

// 初始化 Express 应用
const app = express();

// 中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
app.use(helmet());
app.use(morgan('dev'));

// 路由
app.get('/', (req, res) => {
  res.json({ message: '欢迎使用糖尿病健康管理小程序后端 API' });
});

// API 路由
app.use('/api/users', userRoutes);
app.use('/api/health', healthRoutes);
app.use('/api/test', testRoutes);
app.use('/api/reminders', reminderRoutes);
app.use('/api/diet', dietRoutes);
app.use('/api/exercises', exerciseRoutes);
app.use('/api/devices', deviceRoutes);
app.use('/api/health-knowledge', healthKnowledgeRoutes);
app.use('/api/food', foodRoutes);

// 错误处理
app.use(notFound);
app.use(errorHandler);

// 端口设置
const PORT = process.env.PORT || 5002;

// 启动服务器
app.listen(PORT, () => {
  console.log(`服务器运行在端口 ${PORT}`);
});

module.exports = app; 